import { createSlice } from "@reduxjs/toolkit"
import axios from "axios"

const billStore = createSlice({
    name: 'bill',
    initialState: {
        billList: []
    },
    reducers: {
        setBillList (state, action) {
            state.billList = action.payload
        },
        // 添加账单
        addBill (state, action) {
            state.billList.push(action.payload)
        },
        // 删除账单
        deleteBill (state, action) {
            state.billList.filter(item => item.id === action.payload.id)
        }
    }
})
const { setBillList, addBill, deleteBill } = billStore.actions
const url = 'http://localhost:8888/ka'
const fetchBillList = () => {
    return async (dispatch) => {
        const res = await axios.get(url)
        dispatch(setBillList(res.data))
    }
}
const addBillList = (data) => {
    return async (dispatch) => {
        const res = await axios.post(url,data)
        dispatch(addBill(res.data))
    }
}
const deleteBillList = (id) => {
    return async (dispatch) => {
        const res = await axios.delete(`http://localhost:8888/ka/${id}`)
        dispatch(deleteBill(res.data))
    }
}

export { fetchBillList, addBillList, deleteBillList }

const billReducer = billStore.reducer
export default billReducer